package com.scfinance.SPD;

import com.scfinance.SPD.dao.OrderDaoImpl;
import com.scfinance.SPD.service.SPDImgService;
import com.scfinance.SPD.service.SPDUploadService;
import com.scfinance.SPD.util.Constants;
import com.scfinance.SPD.util.Validator;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;


@SpringBootApplication
@EnableScheduling
public class OutputmwApplication {

    private static String loanOrderId;

    private static String filePath;

    private static String uploadType;

    @Autowired
    private SPDUploadService spdUploadService;

    @Autowired
    private SPDImgService spdImgService;

    private Logger logger = LoggerFactory.getLogger(OutputmwApplication.class);

    public static void main(String[] args) {
        try {
            if (Validator.isNotNull(args) && args.length > 0) {
                System.out.println(args[0]);
                String inputStr = String.valueOf(args[0]);
                String[] keyValue = inputStr.split("#");
                uploadType = keyValue[0];
                if ("orderId".equals(uploadType)) loanOrderId = keyValue[1];
                if ("uploadAlone".equals(uploadType)) loanOrderId = keyValue[1];
                if ("file".equals(uploadType)) filePath = keyValue[1];
            }
            SpringApplication.run(OutputmwApplication.class, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostConstruct
    public void outPutmw() {
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>开始<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>开始<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        try {
            if ("orderId".equals(uploadType)) {
                System.out.println("重新上传图片  开始" + loanOrderId);
                logger.info("重新上传图片  开始" + loanOrderId);
                spdImgService.reUpImage(loanOrderId);
                logger.info("重新上传图片  结束" + loanOrderId);
                loanOrderId = null;
                uploadType = null;
            }else if ("file".equals(uploadType)){
                System.out.println("单独上传图片文件夹" + filePath);
                logger.info("单独上传图片文件夹  开始" + filePath);
                spdImgService.upImgAlone(filePath);
                logger.info("单独上传图片文件夹  结束" + filePath);
                filePath = null;
                uploadType = null;
            }else if ("uploadAlone".equals(uploadType)){
                System.out.println("只进件操作  开始" + loanOrderId);
                logger.info("只进件操作  开始" + loanOrderId);
                spdUploadService.uploadAlone(loanOrderId);
                logger.info("只进件操作  结束" + loanOrderId);
                loanOrderId = null;
                uploadType = null;
            } else {
                saveAppId();
                SPDUpload();
                handleStayPatch();
            }
        } catch (Exception e) {
            logger.info("错误", e);
            e.printStackTrace();
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>结束<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>结束<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
    }

    //	@Scheduled(cron = "* * * * * *")
//    @Scheduled(fixedDelay = 300 * 1000)
    public void saveAppId() throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info("saveAppId time:" + sdf.format(System.currentTimeMillis()));
        System.out.println("saveAppId time:" + sdf.format(System.currentTimeMillis()));

        List<Map<String, Object>> list = spdUploadService.needAppId();
        logger.info("准备获取申请书编号的订单List" + list);
        System.out.println("准备获取申请书编号的订单List" + list);
        for (Map<String, Object> map : list) {
            logger.info(JSONObject.fromObject(map).toString());
            System.out.println(JSONObject.fromObject(map).toString());
            String loanOrderId = (String) map.get("order_id");
            String appId = spdUploadService.getAppid(loanOrderId);
            if (Validator.isNotNull(appId)) {
                Object[] params = {Constants.SPD_SAVE_APPID_SUCCESS, loanOrderId};     //保存appId成功
                spdUploadService.updateSingleFlag(params);
            } else {
                logger.info("订单" + loanOrderId + "没有发送:没有取得appId");
                System.out.println("订单" + loanOrderId + "没有发送:没有取得appId");
                Object[] params = {Constants.SPD_NOT_SEND, loanOrderId};     //没有取得appId
                spdUploadService.updateSingleFlag(params);
            }
        }
    }

    //    @Scheduled(fixedDelay = 300 * 1000)
    public void SPDUpload() throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info("SPDUpload time:" + sdf.format(System.currentTimeMillis()));
        System.out.println("SPDUpload time:" + sdf.format(System.currentTimeMillis()));

        String imgReturn = null;
        List<Map<String, Object>> list = spdUploadService.getCustomerApp();
        for (Map<String, Object> map : list) {
            String appId = (String) map.get("appId");
            String loanOrderId = (String) map.get("order_id");
            if (Validator.isNotNull(appId)) {
                String uploadStr = spdUploadService.uploadApplication(appId, map, loanOrderId);
                JSONObject returnJson = JSONObject.fromObject(uploadStr);
                if (returnJson.containsKey("sysres")
                        && "0000".equals(returnJson.getJSONObject("sysres").getString("errorCode"))) {
                    imgReturn = spdImgService.uploadImage(appId, map, loanOrderId);
                    if ("ok".equals(imgReturn) || "repeat".equals(imgReturn)) {
                        Object[] params = {Constants.SPD_SEND_SUCCESS, loanOrderId};     //发送成功
                        spdUploadService.updateSingleFlag(params);
                        spdUploadService.saveOperationRecord(map, "2000", "导出浦发");
                        spdUploadService.setSPDOutputSuccess(loanOrderId); //设置导出成功
                        spdUploadService.pushSPDEntry(loanOrderId);  //发送推送
                    } else {
                        logger.info("订单" + loanOrderId + "图片上传失败");
                        System.out.println("订单" + loanOrderId + "图片上传失败");
                        Object[] params = {Constants.SPD_IMAGE_UPLOAD_FAIL, loanOrderId};     //图片上传失败
                        spdUploadService.updateSingleFlag(params);
                        spdUploadService.saveOperationRecord(map, "2001", "导出浦发失败");
                        spdUploadService.setSPDOutputDefault(loanOrderId);
                    }
                } else {
                    logger.info("订单" + loanOrderId + "发送失败");
                    System.out.println("订单" + loanOrderId + "发送失败");
                    Object[] params = {Constants.SPD_SEND_FAIL, loanOrderId};      //发送失败
                    spdUploadService.updateSingleFlag(params);
                    spdUploadService.saveOperationRecord(map, "2001", "导出浦发失败");
                    spdUploadService.setSPDOutputDefault(loanOrderId);
                }

            } else {
                logger.info("订单" + loanOrderId + "没有发送:没有取得appId");
                System.out.println("订单" + loanOrderId + "没有发送:没有取得appId");
                Object[] params = {Constants.SPD_NOT_SEND, loanOrderId};     //没有取得appId
                spdUploadService.updateSingleFlag(params);
            }
        }
    }

    //    @Scheduled(fixedRate = 300 * 1000)
    public void handleStayPatch() throws UnsupportedEncodingException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info("searchStayPatch time:" + sdf.format(System.currentTimeMillis()));
        System.out.println("searchStayPatch time:" + sdf.format(System.currentTimeMillis()));

        JSONObject stayPatchJson = JSONObject.fromObject(spdUploadService.searchStayPatch());
        Integer recordamount = stayPatchJson.getInt("recordamount");
        if (recordamount > 0) {
            JSONObject sysres = stayPatchJson.getJSONObject("sysres");
            String errorCode = sysres.getString("errorCode");
            JSONArray rclist = stayPatchJson.getJSONArray("rclist");
            for (Object json : rclist) {
                JSONObject recordJson = JSONObject.fromObject(json);
                String stayPatchMsg = recordJson.getString("returntype");
                String uploadDate = recordJson.getString("receiveddate");
                String appId = recordJson.getString("shenqingshucode");
                Object[] stayPatchParams = {errorCode, stayPatchMsg, uploadDate, appId};
                String loanOrderId = spdUploadService.updateSPDreturn(stayPatchParams);
                if (loanOrderId!=null){
                    logger.info("订单" + loanOrderId + "置为待补件状态");
                    System.out.println("订单" + loanOrderId + "置为待补件状态");
                    Object[] params = {Constants.SPD_SEND_FAIL, loanOrderId};      //发送失败
                    spdUploadService.updateStayPatchFlag(params);
                }
            }
        }
    }

}
